package middleware

import (
	"github.com/kataras/iris/v12"
	"micro-grpc-server/app/common"
	"sync"
)

var MustLogin *mustLoginMiddleware

func init() {
	var once sync.Once
	once.Do(func() {
		MustLogin = &mustLoginMiddleware{}
	})
}

type mustLoginMiddleware struct{}

func (m *mustLoginMiddleware) Process(ctx iris.Context) {
	userId := ctx.Values().Get("auth_user_id")
	if userId == nil {
		ctx.StatusCode(401)
		_, _ = ctx.JSON(common.Response{ErrCode: 401, ErrMsg: "Your request was made with invalid credentials.", Data: nil})
		return
	}
	ctx.Next()
}

func (m *mustLoginMiddleware) ProcessAdmin(ctx iris.Context) {
	if auth := common.SessManager.Start(ctx).Get("auth_admin_user_id"); auth == nil {
		ctx.StatusCode(401)
		_, _ = ctx.JSON(common.Response{ErrCode: 401, ErrMsg: "Your request was made with invalid credentials.", Data: nil})
		return
	}

	ctx.Next()
}
